import { useEffect, useRef, useState } from "react";
import { PageContainer } from "@ant-design/pro-layout";
import useCommonTable from "@/hooks/useCommonTable";
import { fetchList, update, add, remove } from "@/api/class";
import { weekDayOptions } from "@/const";
import courseTypeOptions from "@/courseTypeOptions";
import { history } from "umi";

import {
  ProFormDigit,
  ProFormTextArea,
  ProFormSelect,
  ProFormTimePicker,
} from "@ant-design/pro-form";
import { Button, Row, Col, Tag } from "antd";
import { fetchList as fetchTeacherList } from "@/api/teacher";
import { fetchList as fetchRoomList } from "@/api/room";
import { fetchList as fetchStudentList } from "@/api/student";

export default () => {
  const actionRef = useRef();
  const [teacherList, setTeacherList] = useState([]);
  const [roomList, setRoomList] = useState([]);
  const [studentList, setStudentList] = useState([]);
  const [tabActiveKey, setTabActiveKey] = useState(
    location.hash.split("#/")[1] || "0"
  );

  const getTeacherList = async () => {
    const res = await fetchTeacherList({
      page: 1,
      pageSize: 100,
    });
    const data = res.data?.map((item) => {
      item.key = String(item._id);
      item.tab = item.name;
      return item;
    });
    setTeacherList(data);
  };

  const getRoomList = async () => {
    const res = await fetchRoomList({
      page: 1,
      pageSize: 100,
    });
    setRoomList(res.data);
  };
  const getStudentList = async () => {
    const res = await fetchStudentList({
      page: 1,
      pageSize: 500,
      status: 1,
    });
    setStudentList(res.data);
  };

  useEffect(() => {
    getTeacherList();
    getRoomList();
    getStudentList();
  }, []);

  const columns = [
    {
      title: "教师",
      dataIndex: "teacherId",
      search: false,
      render: (_, record) => {
        return record.teacher.name;
      },
    },

    {
      title: "星期",
      dataIndex: "weekDay",
      valueType: "select",
      fieldProps: {
        options: weekDayOptions,
      },
    },
    {
      title: "上课时间",
      dataIndex: "classTime",
      render: (_, record) => {
        return `${record.classTimeStart}-${record.classTimeEnd}`;
      },
      search: false,
    },
    {
      title: "课程",
      dataIndex: "courseType",
      valueType: "select",
      fieldProps: {
        options: [
          ...courseTypeOptions.map((item) => {
            return {
              label: item.label,
              value: item.value,
            };
          }),
        ],
      },
    },
    {
      title: "教室",
      dataIndex: "roomId",
      valueType: "select",
      fieldProps: {
        options: roomList,
        fieldNames: {
          label: "name",
          value: "_id",
        },
      },
      render: (_, record) => {
        return record.room.name;
      },
    },
    {
      title: "人数",
      dataIndex: "num",
      search: false,
      render: (_, record) => {
        return (
          <>
            <span style={{ color: "red" }}>
              {record.studentIds?.length} / {record.room.num}
            </span>
          </>
        );
      },
    },

    {
      title: "学员列表",
      dataIndex: "studentList",
      search: false,
      width: 200,
      render: (_, record) => {
        return (
          <>
            {record.studentList.map((item) => (
              <Tag
                style={{ marginTop: 10 }}
                color={item.gender === 1 ? "blue" : "magenta"}
              >
                {item.name}
              </Tag>
            ))}
          </>
        );
      },
    },
  ];
  const renderFormItem = ({ type, formRef }) => {
    return (
      <>
        <Row gutter={20}>
          <Col span={12}>
            <ProFormSelect
              width="lg"
              name="courseType"
              label="所属课程"
              allowClear
              fieldProps={{
                showSearch: true,
                filterOption: (input, option) => {
                  return (
                    option.label?.toLowerCase().indexOf(input.toLowerCase()) >=
                    0
                  );
                },
                options: [
                  ...courseTypeOptions.map((item) => {
                    return {
                      label: item.label,
                      value: item.value,
                    };
                  }),
                ],
              }}
              rules={[{ required: true, message: "请选择所属课程" }]}
            />
          </Col>
          <Col span={12}>
            <ProFormDigit
              width="lg"
              label="课时消耗"
              name="lessonConsumption"
              placeholder="请输入课时消耗"
              addonAfter="课时"
              fieldProps={{
                precision: 1,
              }}
              rules={[{ required: true, message: "请输入课时消耗" }]}
            />
          </Col>
        </Row>

        <Row gutter={20}>
          <Col span={12}>
            <ProFormSelect
              width="lg"
              name="teacherId"
              label="教师"
              allowClear
              fieldProps={{
                options: teacherList,
                fieldNames: {
                  label: "name",
                  value: "_id",
                },
              }}
              rules={[{ required: true, message: "请选择教师" }]}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              width="lg"
              name="weekDay"
              label="星期"
              allowClear
              fieldProps={{
                options: weekDayOptions,
              }}
              rules={[{ required: true, message: "请选择星期" }]}
            />
          </Col>
        </Row>
        <Row gutter={20}>
          <Col span={12}>
            <ProFormSelect
              width="lg"
              name="roomId"
              label="教室"
              allowClear
              fieldProps={{
                options: roomList,
                fieldNames: {
                  label: "name",
                  value: "_id",
                },
              }}
              rules={[{ required: true, message: "请选择教室" }]}
            />
          </Col>
          <Col span={12}>
            <ProFormTimePicker.RangePicker
              width="lg"
              label="选择时间"
              name="time"
              placeholder={["开始时间", "结束时间"]}
              fieldProps={{
                format: "HH:mm",
              }}
              transform={(values) => {
                return {
                  classTimeStart: values ? values[0] : undefined,
                  classTimeEnd: values ? values[1] : undefined,
                };
              }}
              rules={[
                {
                  required: true,
                  message: "请选择时间段",
                },
              ]}
            />
          </Col>
        </Row>

        <Row gutter={20}>
          <Col span={12}>
            <ProFormSelect
              width="lg"
              name="studentIds"
              label="学生"
              allowClear
              fieldProps={{
                mode: "multiple",
                showSearch: true,
                filterOption: (input, option) => {
                  console.log("option===", option);
                  return (
                    option.label?.toLowerCase().indexOf(input.toLowerCase()) >=
                    0
                  );
                },
                options: studentList,
                fieldNames: {
                  value: "_id",
                  label: "name",
                },
              }}
              rules={[{ required: true, message: "请选择学生" }]}
            />
          </Col>
          <Col span={12}>
            <ProFormTextArea
              width="lg"
              fieldProps={{
                rows: 5,
              }}
              name="remark"
              label="备注"
              placeholder="请输入备注"
            />
          </Col>
        </Row>
      </>
    );
  };

  return (
    <PageContainer
      tabActiveKey={tabActiveKey}
      onTabChange={(key) => {
        location.hash = `#/${key}`;
        setTabActiveKey(key);
        actionRef.current?.reload();
      }}
      tabList={[
        {
          key: "0",
          tab: "全部",
        },
        ...teacherList,
      ]}
    >
      {useCommonTable({
        actionRef,
        title: "班级",
        renderFormItem,
        initialValues: {
          lessonConsumption: 1.5,
        },
        columns,
        params: {
          teacherId: tabActiveKey == 0 ? "" : tabActiveKey,
        },
        modalWidth: "50%",
        fetchList: async (params) => {
          const res = await fetchList(params);
          res.data = res.data.map((item) => {
            return {
              ...item,
              time: [item.classTimeStart, item.classTimeEnd],
            };
          });

          return res;
        },
        add,
        update,
        remove,
        insertPosition: 3,
        renderOtherAction: (_, record, actionRef) => {
          return (
            <Button
              type="primary"
              onClick={() => {
                history.push(`/class/record?id=${record._id}`);
              }}
            >
              排课记录
            </Button>
          );
        },
        actionColumnWidth: 200,
        showCheckbox: false,
      })}
    </PageContainer>
  );
};
